import 'package:aichat_flutter_wallet/module/module_browser/viewmodel/before_browser.dart';

import 'package:aichat_flutter_wallet/module/module_dapp/utils/dapp_history_util.dart';

import 'package:aichat_flutter_wallet/module/module_dapp/widgets/dapp_history_love_list.dart';

import 'package:aichat_flutter_wallet/module/module_dapp/widgets/dapp_title.dart';

import 'package:aichat_flutter_wallet/module_common/router/routers.dart';

import 'package:aichat_flutter_wallet/module_common/utils/util.dart';

import 'package:aichat_flutter_wallet/module_common/widgets/dialog/dialog_utils.dart';

import 'package:aichat_flutter_wallet/module_common/widgets/page_status_com.dart';

import 'package:flutter/cupertino.dart';

import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:lib_database/sp.dart';

import 'package:lib_util/lib_util.dart';

import '../provider/dapp_cache_provider.dart';

import '../provider/dapp_provider.dart';

import '../utils/dapp_cache_util.dart';

import '../utils/dapp_favorite_util.dart';

import '../widgets/dapp_history_list.dart';

import 'dart:io';

import 'package:lib_database/src/bean.dart';

class DAppHistoryPage extends StatefulWidget {
  String? url;

  DAppHistoryPage({super.key, this.url});

  @override
  State<DAppHistoryPage> createState() => _DAppHistoryPageState();
}

class _DAppHistoryPageState extends State<DAppHistoryPage> {
  List<DAppBean> searchList = [];

  TextEditingController _textEditingController = TextEditingController();

  FocusNode _focusNode = FocusNode();

  String _inputText = '';

  // 当前键盘是否是激活状态

  bool isKeyboardActived = false;

  @override
  void activate() {
    // TODO: implement activate
    super.activate();
  }

  @override
  void initState() {
    super.initState();

    _textEditingController.text = widget.url ?? "";

    _inputText = widget.url ?? "";

    if (_inputText.isNotEmpty) {
      final List<DAppBean> cacheDAppList = context.read<DAppCacheProvider>().cacheDAppList.reversed.toList();

      searchList = cacheDAppList.where((obj) {
        if (obj.url!.length > 0) {
          return obj.url.toString().indexOf(_inputText) > -1;
        }

        return obj.name.toString().indexOf(_inputText) > -1;
      }).toList();
    }

    _focusNode.addListener(_onFocus);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_focusNode);

      if (Platform.isAndroid && _focusNode.hasFocus) {
        if (isKeyboardActived) {
          isKeyboardActived = false;

          _focusNode.unfocus();

          return;
        }

        isKeyboardActived = true;
      }
    });

    // fetchData();
  }

  // Future<void> fetchData() async {

  //   try{

  //     await Provider.of<DAppCacheProvider>(context, listen: false)

  //         .refreshCacheDAppList('1');

  //   }catch(e){

  //     print(e);

  //   }

  // }

  _onFocus() {
    if (_focusNode.hasFocus) {
      FocusScope.of(context).requestFocus(_focusNode);

      // 聚焦时候的操作

      return;
    }

    isKeyboardActived = false;
  }

  doGotoBrowser({required String webUrl, BuildContext? context, Function? callback}) {
    if (webUrl.isEmpty) return;

    String url = '';

    if (!webUrl.startsWith('http') && !webUrl.startsWith('https')) {
      url = 'https://' + webUrl;
    } else {
      url = webUrl;
    }

    var list = SP().getBrowserInsideValid();

    if (!list.contains(url)) {
      DialogUtils.showBrowserInside(context: context!, url: url);
    } else {
      if (callback != null) {
        callback();
      }

      goBrowser(url: url);
    }
  }

  @override
  void dispose() {
    _focusNode.unfocus();

    _focusNode.dispose();

    _textEditingController.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final double statusBarHeight = MediaQuery.of(context).padding.top;

    // TODO: implement build

    return Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: Colors.white,
        body: Consumer2<DAppCacheProvider, DAppProvider>(builder: (c, model, model2, child) {
          final List<DAppBean> cacheDAppList = model.cacheDAppList.reversed.toList();

          final List<DAppBean> favoriteDAppList = model2.favoriteDAppList.toList();

          return Column(
            children: [
              Container(
                color: Colors.white,
                height: (statusBarHeight + 44 + 10).w,
                padding: EdgeInsets.only(top: (statusBarHeight + 10).w, left: 10.w, right: 20.w, bottom: 8.w),
                child: Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        Navigator.of(context).popUntil((router) => router.settings.name == Routes.rootRoute);
                      },
                      child: Container(
                        margin: EdgeInsets.only(left: 0),
                        padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 4.w, bottom: 4.w),
                        child: Image.asset(
                          'assets/images/dapp/history_goback.png',
                          width: 20.w,
                          height: 30.w,
                        ),
                      ),
                    ),
                    Expanded(
                        flex: 1,
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8.w),
                            color: Color.fromRGBO(246, 246, 246, 1),
                          ),
                          padding: EdgeInsets.only(left: 15.w, top: 0, right: 5.w, bottom: 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Container(
                                margin: EdgeInsets.only(right: 5.w, bottom: 5.w, top: 5.w),
                                child: Image.asset(
                                  'assets/images/dapp/search.png',
                                  width: 20.w,
                                  height: 20.w,
                                ),
                              ),
                              Expanded(
                                flex: 1,
                                child: Stack(
                                  alignment: Alignment.centerLeft,
                                  children: [
                                    Container(
                                      margin: EdgeInsets.symmetric(vertical: 10.w),
                                      decoration: BoxDecoration(
                                        color: Colors.transparent,
                                      ),
                                    ),
                                    Positioned(
                                        bottom: 0,
                                        left: 0,
                                        top: 0,
                                        right: 0,
                                        child: Container(
                                          padding: EdgeInsets.symmetric(horizontal: 10.w),
                                          child: Center(
                                            child: TextField(
                                              textAlignVertical: TextAlignVertical.bottom,
                                              inputFormatters: [
                                                LengthLimitingTextInputFormatter(8182),

                                                // 限制输入长度为20个字符
                                              ],
                                              keyboardType: TextInputType.text,
                                              controller: _textEditingController,
                                              focusNode: _focusNode,
                                              onTapOutside: (PointDownEvent) {
                                                _focusNode.unfocus();
                                              },
                                              textInputAction: TextInputAction.done,
                                              onEditingComplete: () {
                                                _focusNode.unfocus();
                                              },
                                              onChanged: (value) {
                                                final List<DAppBean> filteredNumbers = cacheDAppList.where((obj) {
                                                  if (obj.url!.length > 0) {
                                                    return obj.url.toString().indexOf(value) > -1;
                                                  }

                                                  return obj.name.toString().indexOf(value) > -1;
                                                }).toList();

                                                setState(() {
                                                  _inputText = value;

                                                  searchList = filteredNumbers;
                                                });
                                              },
                                              cursorColor: Color.fromRGBO(134, 103, 254, 1),
                                              style: TextStyle(
                                                fontSize: 15.sp,
                                                color: Color.fromRGBO(51, 51, 51, 1),
                                                fontWeight: FontWeight.w400,
                                              ),
                                              decoration: InputDecoration(
                                                contentPadding: EdgeInsets.only(bottom: 15.w),
                                                border: InputBorder.none,
                                                hintText: 'Search or type URL',
                                                hintStyle: TextStyle(
                                                  fontSize: 14.sp,
                                                  color: Color.fromRGBO(190, 189, 202, 1),
                                                ),
                                              ),
                                              maxLines: 1,
                                              minLines: 1,
                                            ),
                                          ),
                                        )),
                                  ],
                                ),
                              ),
                              Visibility(
                                  visible: _inputText.length > 0,
                                  child: Container(
                                    width: 20.w,
                                    height: 20.w,
                                    margin: EdgeInsets.only(right: 10.w),
                                    child: GestureDetector(
                                      onTap: () {
                                        _textEditingController.clear();

                                        setState(() {
                                          _inputText = '';
                                        });
                                      },
                                      child: Image.asset(
                                        'assets/images/dapp/history_input_close.png',
                                        width: 20.w,
                                        height: 20.w,
                                      ),
                                    ),
                                  )),
                              GestureDetector(
                                onTap: () async {
                                  doGotoBrowser(webUrl: _inputText, context: context, callback: () {});
                                },
                                onTapDown: (params) {
                                },
                                child: Container(
                                  alignment: Alignment.center,
                                  margin: EdgeInsets.only(top: 3.w, bottom: 3.w),
                                  padding: EdgeInsets.only(left: 7.w, right: 7.w, top: 5.w, bottom: 5.w),
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(8.w),
                                    color: _inputText.length > 0
                                        ? Color.fromRGBO(134, 103, 254, 1)
                                        : Color.fromRGBO(134, 103, 254, 1),
                                  ),
                                  child: Text(
                                    'GO',
                                    style: TextStyle(
                                        color:
                                            _inputText.length > 0 ? Colors.white : Color.fromRGBO(255, 255, 255, 0.4),
                                        fontWeight: FontWeight.w500,
                                        fontSize: 14.sp),
                                  ),
                                ),
                              )
                            ],
                          ),
                        ))
                  ],
                ),
              ),
              Expanded(
                  flex: 1,
                  child: Container(
                    child: Column(
                      children: [
                        if (_inputText.length <= 0)
                          DAppTitle(
                              title: 'History',
                              rightDom: GestureDetector(
                                  onTap: () {
                                    if (cacheDAppList.length == 0) return;

                                    DAppHistoryUtil.setConfirmBottomDialog(context, title: 'Delete the history?',
                                        onConfirm: () {
                                      DAppCacheUtil.deleteAllHistory(context, dApps: cacheDAppList);
                                    }, onCancel: () {
                                      // print('正在为您 取消');
                                    });
                                  },
                                  behavior: HitTestBehavior.translucent,
                                  child: Container(
                                    color: Colors.transparent,
                                    padding: EdgeInsets.only(left: 32.w),
                                    child: Image.asset(
                                      'assets/images/dapp/delete.png',
                                      width: 16.w,
                                      height: 16.w,
                                    ),
                                  ))),
                        if (_inputText.length <= 0 && cacheDAppList.length > 0)
                          SizedBox(
                            height: 10.w,
                          ),
                        if (_inputText.length <= 0 && cacheDAppList.length > 0)
                          Expanded(
                            child: ListView.builder(
                                padding: EdgeInsets.all(0),
                                itemCount: cacheDAppList.length >= 6 ? 6 : cacheDAppList.length,
                                itemBuilder: (BuildContext buildContext, int index) {
                                  DAppBean item = cacheDAppList[index];

                                  return DAppHistoryList(
                                      image: item.logo as String,
                                      name: item.name as String,
                                      description: item.url as String,
                                      onClick: () {
                                        doGotoBrowser(webUrl: item.url as String, context: context);
                                      },
                                      onDelete: () {
                                        DAppHistoryUtil.setConfirmBottomDialog(
                                          context,
                                          title: 'Delete the history?',
                                          onConfirm: () {
                                            DAppCacheUtil.deleteHistoryOne(context, dApp: item);
                                          },
                                        );
                                      });
                                }),
                          ),
                        if (_inputText.length > 0 && searchList.length == 0)
                          Column(children: [
                            SizedBox(
                              height: 100.w,
                            ),
                            PageEmptyCom(type: 'nofound'),
                          ]),
                        if (_inputText.length > 0 && searchList.length > 0)
                          Expanded(
                            child: ListView.builder(
                                padding: EdgeInsets.all(0),
                                itemCount: searchList.length,
                                itemBuilder: (BuildContext buildContext, int index) {
                                  var item = searchList[index];

                                  final DAppBean? isFavoriteItem = favoriteDAppList.length > 0
                                      ? favoriteDAppList.firstWhereOrNull((element) => element.url == item.url)
                                      : null;

                                  bool isBool = isFavoriteItem != null && isFavoriteItem != {};

                                  return DAppHistoryLoveList(
                                      isLove: isBool,
                                      searchContent: _inputText,
                                      image: item.logo as String,
                                      name: item.name as String,
                                      description: item.url as String,
                                      onClick: () {
                                        // print('url：' + item.url.toString());
                                        goBrowser(url: item.url.toString());
                                      },
                                      onLove: () {
                                        DAppFavoriteUtil.showSetFavorite(context,
                                            onConfirm: () {}, onClose: () {}, DApp: item);
                                      });
                                }),
                          )
                      ],
                    ),
                  ))
            ],
          );
        }));
  }
}
